<script setup>
  import { onMounted, ref } from "vue";
  import {
    getSelectStatusListAPI,
    getUpdateCommodityUpAPI,
    getUpdateCommodityCheckAPI,
  } from "@/server/api/ShopFollow";
  import { useRoute, useRouter } from "vue-router";
  import { useUseStore } from "@/stores/user";
  import { Toast, showDialog } from "vant";
  import {
    selectShopInfoListByShopId,
    deleteShopInfoById,
    deleteCommodityIdById
  } from "@/server/api/shopApi.js";
  import { useI18n } from "vue-i18n";
  import { ToastFun } from "@/hook/toast";
  const { t } = useI18n();
  const route = useRoute();
  const router = useRouter();
  const actions = [
    { text: "Pl-10%", color: "#d1c0dd", showPopover: false },
    { text: "Pl-20%", color: "#d1c0dd", showPopover: false },
    { text: "Pl-30%", color: "#d1c0dd", showPopover: false },
    { text: "Pl-50%", color: "#d1c0dd", showPopover: false },
  ];

  let text = "Pl-50%";
  const onSelect = (action) => {
    text = action.text;
  };
  const baseURL = useUseStore().ing;
  const lists = ref([]);
  const list = ref({});
  const limit = ref(9)
  let page = ref(1);
  const loading = ref(false);
  const finished = ref(false);
  //修改积分的值
  const price = ref(null);
  //修改积分隐藏
  const updateDiv = ref(false);
  // 列表接口
  const selectStatusListFun = async (limit, page, shopId) => {
    try {
      const res = await getSelectStatusListAPI(limit, page, shopId);
      // 如果接口没有返回 list 或 list 为空，停止请求
      if (!res.data?.data?.list || res.data.data.list.length === 0) {
        finished.value = true; // 标记为加载完成
        return;
      }
      // 如果 commodityImgList 是字符串，分割成数组
      res.data.data.list.forEach((item) => {
        if (item.commodityImgList && typeof item.commodityImgList === "string") {
          item.commodityImgList = item.commodityImgList.split(","); // 按 `,` 分割成数组
        }
      });

      // 将数据添加到列表
      lists.value.push(...res.data.data.list);

      // 如果返回数据量少于当前请求的限制值，标记为完成
      if (res.data.data.list.length < limit.value) {
        finished.value = true; // 数据已加载完
      }
    } catch (error) {
      console.error("加载列表失败:", error);
      ToastFun("error", { msg: t("common.error") });
    } finally {
      loading.value = false;
    }
  };

  const onLoad = () => {
    if (loading.value || finished.value) return;  // 检查是否正在加载或者已加载完
    loading.value = true;
    selectStatusListFun(limit.value, ++page.value, list.value.shopId);
  };

  //实体店商品下架接口
  const upToDown = async (commodityId, index) => {
    ToastFun("Loading", { duration: 3000 });
    const res = await getUpdateCommodityUpAPI(commodityId);
    if (res.data.code === 200) {
      lists.value[index].status = 1;
      ToastFun(t("pay.success2"));
    }

  };

  //实体店商品上架接口
  const downToUp = async (commodityId, index) => {
    ToastFun("Loading", { duration: 3000 });
    const res = await getUpdateCommodityCheckAPI(commodityId);
    if (res.data.code === 200) {
      lists.value[index].status = 0;
      ToastFun(t("pay.success2"));
    }
  };
  // // 过滤status为2的商品
  // const filterCount = computed(() => {
  //   return lists.value.filter((item) => item.status !== 2);
  // });

  // 跳转粉丝页面
  const goShopFans = () => {
    router.push({
      path: "/StoreFans",
      query: {
        id: list.value.shopId,
      },
    });
  };

  // 跳转实体店详情页
  const goShopDetail = () => {
    router.push({
      path: "/shopDetail",
      query: { id: list.value.shopId },
    });
  };
  //根据id删除商店铺
  const deleteShop = async (id) => {

    const goodsRes = await selectShopInfoListByShopId(id);
    if (goodsRes.data.data.length > 0) {
      showDialog({
        tittle: t("mShopLChild.title"),
        message: t("mShopLChild.message"),
        theme: "round-button",
        confirmButtonColor: "#58137a",
      });
      return;
    }
    const res = await deleteShopInfoById(id);
    if (res.data.code === 200) {
      ToastFun(t("pay.success2"));
      router.push("/MangeShopList");
    } else {
      ToastFun("");
    }
  };
  const toedit = (i) => {
    const categoryId = JSON.parse(route.query.data).categoryId;
    if (categoryId == "sdfsd" || categoryId == "fwefw" || categoryId == "dfssd") {
      router.push({
        path: "/hotelMerchandise",
        query: { data: i.commodityId, status: 1 },
      });
    } else {
      router.push({ path: "/updateItem", query: { id: i.commodityId } });
    }
  };
  onMounted(() => {
    if (!finished.value) {
      list.value = JSON.parse(route.query.data);
      selectStatusListFun(limit.value, page.value, list.value.shopId);
    }
  });


  const deleteCommodityId = async (id) => {
    ToastFun("Loading", {
      duration: 0
    });
    const res = await deleteCommodityIdById(id)
    if (res.data.code === 200) {
      lists.value = [];
      selectStatusListFun(limit.value, page.value, list.value.shopId);
      ToastFun("show", {
        msg: t("shopSeller.delete3")
      });
    } else {
      ToastFun("fail", {
        msg: t("shopSeller.delete4")
      });
    }
  }

</script>

<template>
  <TopButtonCenter :title="$t('me.manage.shop.title')" />

  <div class="mask"></div>

  <div class="ManageShopSubset">
    <header>
      <div class="left">
        <div class="login" @click="goShopDetail()">
          <!-- <img v-lazy="list.userImage" alt="" /> -->
          <img :src="list.userImage || `/images/pipayshop_logo.png`" alt="" />
        </div>
        <div class="right_tex">
          <h5>{{ list.shopName }}</h5>
          <div class="totol">
            <span @click="goShopFans()">{{ list.follows }} Fans</span>
            {{ list.score }}
            <van-rate v-model="list.score" :size="15" :count="5" color="#ffd21e" void-icon="star" void-color="#eee"
              readonly />
          </div>
        </div>
      </div>
      <div class="right">
        <!-- 编辑图片按钮 -->
        <img class="editImg" src="/images/edit.png" @click="
    $router.push({
      path: '/updateShopInfo',
      query: { id: list.shopId },
    })
    " />
        <!-- 删除店铺按钮 -->
        <img class="rubbishImg" src="/images/rubbish.png" @click="deleteShop(list.shopId)" />
      </div>
    </header>

    <ul class="list">
      <van-list v-model:loading="loading" :finished="finished" :finished-text="$t('shop.shopList.finish')"
        :immediate-check="false" @load="onLoad">
        <li class="box_show" v-for="(i, index) in lists" :key="index">
          <div class="login">
            <img v-lazy="i.commodityImgList[0]" alt="" />
          </div>

          <div class="text_ad">
            <p>{{ i.commodityName }}</p>
            <div class="btn_res" v-if="false">
              <van-popover v-model:show="actions.showPopover" :tabindex="index" :actions="actions" @select="onSelect">
                <template #reference>
                  <div class="button">{{ text }}</div>
                </template>
              </van-popover>
            </div>

            <div class="btnList">
              <!-- 修改商品按钮 -->
              <div class="button" @click="toedit(i)">
                {{ $t("mShopLChild.update") }}
              </div>
              <div class="button" v-if="i.status == 0" @click="upToDown(i.commodityId, index)">
                {{ $t("me.manage.down") }}
              </div>
              <div class="button" v-else-if="i.status == 1" @click="downToUp(i.commodityId, index)">
                {{ $t("me.manage.up") }}
              </div>
              <div class="button" v-else-if="i.status == 2">审核中</div>
            </div>

          </div>
          <div style="">
            <img style="width: 30rem;" src="/images/rubbish.png" @click="deleteCommodityId(i.commodityId)" />
          </div>
        </li>
      </van-list>
    </ul>
  </div>
</template>
<style lang="scss" scoped>
  .mask {
    height: 60rem;
  }

  .ManageShopSubset {
    font-size: 14rem;
    padding: 0 10rem;

    header {
      margin-bottom: 30rem;
      display: flex;
      padding: 10rem 0;
      border-bottom: 1rem solid #d2d2d2;

      .left {
        display: flex;

        .right_tex {
          position: relative;
          line-height: 30rem;
          margin: 0 10rem;

          >h5 {
            font-size: 16rem;
            font-weight: 500;
          }

          .totol {
            color: #d2d2d2;
          }
        }

        .login {
          width: 70rem;
          height: 70rem;

          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }
      }

      .right {
        margin-left: 40rem;

        //编辑图片
        .editImg {
          width: 35px;
          height: 35px;
          margin-right: 23rem;
        }

        //垃圾桶图片
        .rubbishImg {
          width: 35px;
          height: 35px;
        }
      }

      //编辑图片
    }

    .list {
      li {
        box-sizing: border-box;
        margin-bottom: 10rem;
        padding: 10rem 0;
        display: flex;
        justify-content: space-between;
        border-radius: 12rem;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0rem 5rem 15rem rgba(206, 199, 212, 0.1);

        .login {
          width: 80rem;
          height: 80rem;
          border-radius: 12rem;

          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        .text_ad {
          position: relative;
          width: 100%;
          display: flex;
          flex-direction: column;
          margin: 0 10rem;

          .btn_res {
            position: absolute;
            top: 25rem;
            right: -8rem;

            :deep(.van-popover__wrapper) {
              .button {
                text-align: center;
                width: 105rem;
                border-radius: 10rem;
                height: 32rem;
                line-height: 32rem;
                color: #642e8e;
                background-color: #d1c0dd;
              }
            }
          }

          p {
            font-size: 16rem;
            width: max-content;

            /** 文本1 */
            font-size: 16rem;
            font-weight: 400;
            letter-spacing: 0rem;
            line-height: 24rem;
            color: rgba(51, 51, 51, 1);
            text-align: left;
            vertical-align: top;
          }

          .btnList {
            margin-top: 22rem;
            display: flex;

            .button {
              box-sizing: border-box;
              width: 115rem;
              height: 32rem;
              opacity: 1;
              border-radius: 220rem;
              margin-right: 10rem;
              line-height: 32rem;
              text-align: center;
              color: #642e8e;
              border-radius: 20rem;
              border: 2rem solid;
              font-weight: 600;
            }
          }
        }

      }
    }
  }
</style>